package com.lagou;

import com.lagou.config.LoadBalanse;
import com.lagou.controller.TestController;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.io.IOException;
import java.util.*;

@SpringBootApplication
public class ClientBootStrap implements Watcher {

    private static final String BASE_SERVICE = "/zookeeper";

    private static final String SERVICE_NAME = "/server";
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws InterruptedException, IOException {

        ConfigurableApplicationContext context = SpringApplication.run(ClientBootStrap.class);
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new ClientBootStrap());
        updateServerList();
        while (true) {
            Map<String, Object> map = new HashMap<>();
            TestController testController = new TestController();
            System.out.println(testController.getProduct(map));
            Thread.sleep(5000);
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println("------------" + watchedEvent.toString());
        if (watchedEvent.getType() == Watcher.Event.EventType.NodeChildrenChanged && watchedEvent.getPath().equals(BASE_SERVICE + SERVICE_NAME)) {
            updateServerList();
        }
    }

    public static void updateServerList() {
        List<String> newServiceList = new ArrayList<>();
        try {
            List<String> children = zooKeeper.getChildren(BASE_SERVICE + SERVICE_NAME, true);
            for (String subNode : children) {
                byte[] data = zooKeeper.getData(BASE_SERVICE + SERVICE_NAME + "/" + subNode, false, null);
                String host = new String(data, "utf-8");
                System.out.println("=================host：" + host);
                newServiceList.add(host);
            }
            LoadBalanse.SERVICE_LIST = newServiceList;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
